﻿Imports System.Data
Imports System.Data.SqlClient

Partial Class FSE_Master_Page
    Inherits System.Web.UI.MasterPage
    Public departmentConnectionString As String = ConfigurationManager.ConnectionStrings("FSEdepartmentsConnection").ConnectionString
    Public membershipConnectionString As String = ConfigurationManager.ConnectionStrings("FSEmembershipConnection").ConnectionString
    Public departmentConnectionString2 As String = _
        "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Departments.mdf;Integrated Security=True;User Instance=True"
    Public membershipConnectionString2 As String = _
        "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|mDB.mdf;Integrated Security=True;User Instance=True"




    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not Page.IsPostBack Then
            If Request.IsAuthenticated = True Then

                Dim currentUser As MembershipUser = Membership.GetUser()
                If Not currentUser Is Nothing Then
                    Dim currentUserID As Guid = CType(currentUser.ProviderUserKey, Guid)
                    Call getUserdata(currentUserID)

                    Dim properName As String
                    On Error Resume Next
                    properName = UCase(Left(Me.fName, 1)) & Right(Me.fName, Len(Me.fName) - 1)
                    On Error Resume Next
                    welcome.Text = "Welcome back, "
                    welcomeName.Text = " " & properName
                    welcomeName.Visible = True
                    logout.Visible = True
                    signup.Visible = False
                    login.Style.Add(HtmlTextWriterStyle.Display, "none")
                    On Error GoTo 0

                End If

            Else
                On Error Resume Next
                welcome.Text = "Welcome to Free Student Exchange"
                welcomeName.Visible = False
                logout.Visible = False
                signup.Visible = True
                login.Style.Add(HtmlTextWriterStyle.Display, "inline")
                On Error GoTo 0

            End If


        End If


    End Sub



    Protected Function getUserdata(ByRef Username As Guid)

        Dim conn As New SqlConnection(membershipConnectionString)
        Dim query1 As String = "Select m.[Email], p.firstname [FirstName] " & _
            "from aspnet_Membership m inner join UserProfiles p on p.UserId = m.UserId where (m.[UserId]=@myUsername)"
        Dim cmd As New SqlCommand(query1, conn)
        Dim email As String, fname As String

        email = ""
        fname = ""

        Dim myUsername As New SqlParameter("@myUsername", SqlDbType.UniqueIdentifier)
        myUsername.Value = Username
        cmd.Parameters.Add(myUsername)

        Try

            conn.Open()
            Dim myReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleResult)

            While myReader.Read()
                email = myReader("Email").ToString
                fname = myReader("FirstName").ToString
            End While

            Me.Email = email
            Me.fName = fname


            conn.Close()
            Return True
        Catch ex As Exception

            Response.Redirect("error.aspx", True)
            Return False
        End Try



    End Function


    Public Property fName() As String
        Get
            Return CType(ViewState("fname"), String)
        End Get
        Set(ByVal value As String)
            ViewState("fname") = value
        End Set
    End Property

    Public Property lName() As String
        Get
            Return CType(ViewState("lname"), String)
        End Get
        Set(ByVal value As String)
            ViewState("lname") = value
        End Set
    End Property

    Public Property Email() As String
        Get
            Return CType(ViewState("email"), String)
        End Get
        Set(ByVal value As String)
            ViewState("email") = value
        End Set
    End Property

    Public Property UserID() As String
        Get
            Return CType(ViewState("userid"), String)
        End Get
        Set(ByVal value As String)
            ViewState("userid") = value
        End Set
    End Property


    Protected Sub logout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles logout.Click
        FormsAuthentication.SignOut()

        Session.Clear() 'clear session
        Session.Abandon() 'Abandon session
        Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.Cache.SetNoStore()
        Response.Redirect("Home.aspx")
    End Sub

    Protected Sub floatingButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles floatingButton.Click

        Dim myUser As MembershipUser = Membership.GetUser(username_input.Text)
       

        If Not myUser Is Nothing Then
            If myUser.IsApproved = False Then
                Dim myGuid As Guid = myUser.ProviderUserKey
                Session.Add("userID", myGuid)
                Response.Redirect("notauthenticated.aspx?user=" & username_input.Text)
                Exit Sub
            ElseIf Membership.ValidateUser(username_input.Text, password_input.Text) Then
                floatwarn.Visible = False
                Dim myurl As String = Request.Url.AbsolutePath
                Session.Add("myurl", myurl)
                FormsAuthentication.RedirectFromLoginPage(username_input.Text, False)
                Exit Sub
            ElseIf Not Membership.ValidateUser(username_input.Text, password_input.Text) Then
                floatwarn.Visible = True
            End If
            floatwarn.Visible = True
        Else
            floatwarn.Visible = True
        End If



    End Sub
End Class

